package com.ctgu.entity;

import com.ctgu.config.NettyConfig;
import com.ctgu.service.ChatInBoundHandler;
import com.ctgu.service.ChatOutFilter;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

import javax.annotation.Resource;

public class NettyServer {
    @Resource
    NettyConfig config;

    public void start() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup loopGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, loopGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new WebSocketServerProtocolHandler("/wc"));
                            pipeline.addLast(new ChatOutFilter());
                            pipeline.addLast(new ChatInBoundHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.bind(config.getPort()).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully().sync();
            loopGroup.shutdownGracefully().sync();
        }
    }
}
